<template>
  <div>
    <el-row :gutter="15">
      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right"  :disabled="setting.readonly" >
        <template >
<!--          v-if="!loading && formOperates"-->
          <el-card class="mb-20" shadow ="always" header="基础信息">
            <el-col  :span="8" v-if="judgeShow('project')" >
              <el-form-item  label="项目"  v-if="judgeShow('project')"
                             prop="project" >
                <el-input   v-model="dataForm.project"
                            placeholder="请输入"    clearable  :style='{"width":"100%"}'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('customerName')" >
              <el-form-item  label="客户名称"  v-if="judgeShow('customerName')"
                             prop="customerName" >
                <el-input   v-model="dataForm.customerName"
                            placeholder="请输入"  :disabled="judgeWrite('customerName')"  clearable  :style='{"width":"100%"}'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('contractNo')" >
              <el-form-item  label="合同编号"  v-if="judgeShow('contractNo')"
                             prop="contractNo" >
                <el-input   v-model="dataForm.contractNo"
                            placeholder="请输入"  :disabled="judgeWrite('contractNo')"  clearable  :style='{"width":"100%"}'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('paymentBy')" >
              <el-form-item  label="付款方"  v-if="judgeShow('paymentBy')"
                             prop="paymentBy" >
                <el-input   v-model="dataForm.paymentBy"
                            placeholder="请输入"  :disabled="judgeWrite('paymentBy')"  clearable  :style='{"width":"100%"}'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('billType')" >
              <el-form-item  label="账单类型"  v-if="judgeShow('billType')"
                             prop="billType" >
                <el-input   v-model="dataForm.billType"
                            placeholder="请输入"  :disabled="judgeWrite('billType')"  clearable  :style='{"width":"100%"}'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('expenseStartDate')" >
              <el-form-item  label="计费开始日期"  v-if="judgeShow('expenseStartDate')"
                             prop="expenseStartDate" >
                <el-date-picker   v-model="dataForm.expenseStartDate"
                                  placeholder="请选择"  :disabled="judgeWrite('expenseStartDate')"  clearable  :style='{"width":"100%"}' type="date"  format="yyyy-MM-dd"  value-format="timestamp" >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('expenseEndDate')" >
              <el-form-item  label="计费结束日期"  v-if="judgeShow('expenseEndDate')"
                             prop="expenseEndDate" >
                <el-date-picker   v-model="dataForm.expenseEndDate"
                                  placeholder="请选择"  :disabled="judgeWrite('expenseEndDate')"  clearable  :style='{"width":"100%"}' type="date"  format="yyyy-MM-dd"  value-format="timestamp" >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col  :span="6" v-if="judgeShow('planReceiptDate')" >
              <el-form-item  label="应收日期"  v-if="judgeShow('planReceiptDate')"
                             prop="planReceiptDate" >
                <el-input   v-model="dataForm.planReceiptDate"
                            placeholder="请输入"  :disabled="judgeWrite('planReceiptDate')"  clearable  :style='{"width":"100%"}'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="8" v-if="judgeShow('billRemark')" >
              <el-form-item  label="账单备注"  v-if="judgeShow('billRemark')"
                             prop="billRemark" >
                <el-input   v-model="dataForm.billRemark"
                            placeholder="请输入"  :disabled="judgeWrite('billRemark')"  :style='{"width":"100%"}' true  type="textarea"  :autosize='{"minRows":4,"maxRows":4}' >
                </el-input>
              </el-form-item>
            </el-col>
          </el-card>
          <el-card class="mb-20" shadow ="always" header="费用项">
            <el-col :span="24"   v-if="judgeShow('zcbillitemList')" >
              <el-form-item label-width="0">
                <div class="JNPF-common-title">
                  <h2>设计子表</h2>
                </div>
                <el-table :data="dataForm.zcbillitemList" size='mini' >
                  <el-table-column type="index" width="50" label="序号" align="center" />
                  <el-table-column  label="费用项"  v-if="judgeShow('zcbillitemList-expenseItem')"
                                    prop="expenseItem" >
                    <template slot="header">
                      <span class="required-sign"  v-if="judgeRequired('zcbillitemList-expenseItem')">*</span>费用项
                    </template>
                    <template slot-scope="scope">					<el-select   v-model="scope.row.expenseItem"
                                                                        placeholder="请选择"  :disabled="judgeWrite('zcbillitemList')||judgeWrite('zcbillitemList-expenseItem')"  clearable  :style='{"width":"100%"}'>
                      <el-option v-for="(item, index) in zcgl_cw_bill_itemexpenseItemOptions" :key="index" :label="item.fullName" :value="item.id"  ></el-option>
                    </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column  label="应收(本)金额"  v-if="judgeShow('zcbillitemList-receiveAmount')"
                                    prop="receiveAmount" >
                    <template slot="header">
                      <span class="required-sign"  v-if="judgeRequired('zcbillitemList-receiveAmount')">*</span>应收(本)金额
                    </template>
<!--                    :disabled="judgeWrite('zcbillitemList')||judgeWrite('zcbillitemList-receiveAmount')"-->
                    <template slot-scope="scope">					<el-input   v-model="scope.row.receiveAmount"
                                                                       placeholder="请输入"    clearable  :style='{"width":"100%"}'>
                    </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="50"   v-if="!judgeWrite('zcbillitemList')">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" class="JNPF-table-delBtn" @click="delzcbillitemList(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="table-actions" @click="addzcbillitemList()"  v-if="!judgeWrite('zcbillitemList')">
                  <el-button type="text" icon="el-icon-plus">添加</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-card>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
    <SelectDialog v-if="selectDialogVisible" :config="addTableConf" :formData="dataForm" ref="selectDialog" @select="addForSelect" @close="selectDialogVisible=false"/>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import SelectDialog from '@/components/SelectDialog'
export default {
  components: {SelectDialog  },
  props: [],
  data() {
    return {
      selectDialogVisible: false,
      tableKey: '',
      addTableConf:{},
      loading: false,
      visible: false,
      setting:{},
      eventType: '',
      userBoxVisible:false,
      tableRequiredData: {},
      primaryKeyPolicy:true,
      dataForm: {
        id:'',
        flowId: '',
        status: 1,
        candidateList:{},
        freeapproveruserid: '',
        branchList:[],
        errorRuleUserList:{},
        flowUrgent: 1,
        version:0,
        flowtaskid:undefined,
        copyIds:'',
        project : '',
        customerName : '',
        contractNo : '',
        paymentBy : '',
        billType : '',
        expenseStartDate : '',
        expenseEndDate : '',
        planReceiptDate : '',
        billRemark : '',
        zcbillitemList:[],
      },
      dataRule:
        {
        },
      zcgl_cw_bill_itemexpenseItemOptions:[{"fullName":"选项一","id":"1"},{"fullName":"选项二","id":"2"}],
      zcgl_cw_bill_itemexpenseItemProps:{"label":"fullName","value":"id"},
    }
  },
  computed: {
    formOperates() {
      return this.setting.formOperates;
    }
  },
  watch: {},
  created() {
    this.dataAll()
  },
  mounted() {},
  methods: {
    updateDataRule() {
      let newRules = {}
      for (let i = 0; i < this.setting.formOperates.length; i++) {
        const item = this.setting.formOperates[i]
        if (!item.id.includes('-')) {
          const newRulesItem = {
            required: item.required || false,
            message: item.name + '不能为空',
            trigger: item.trigger || 'blur'
          }
          if (!this.dataRule.hasOwnProperty(item.id)) {
            if (item.required) this.$set(newRules, item.id, [newRulesItem])
          } else {
            let withoutRequiredItem = true
            for (let i = 0; i < this.dataRule[item.id].length; i++) {
              if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                this.dataRule[item.id][i].required = item.required || false
                withoutRequiredItem = false
              }
            }
            if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
          }
        } else {
          let key = item.id.split('-')[0]
          let newId = item.id.split('-')[1]
          let newItem = {
            ...item,
            id: newId
          }
          if (!this.tableRequiredData.hasOwnProperty(key)) {
            this.$set(this.tableRequiredData, key, [newItem])
          } else {
            this.tableRequiredData[key].push(newItem)
          }
        }
      }
      this.dataRule = { ...this.dataRule, ...newRules }
    },
    exist() {
      let isOk = true;
      let messageList = [];
      for (let key in this.tableRequiredData) {
        let arr = this.tableRequiredData[key].filter((o) => o.required) || [];
        for (let k = 0; k < arr.length; k++) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let id = arr[k].id;
            let name = arr[k].name;
            let _data = this.dataForm[key][i][id];
            let boo = true;
            if (Array.isArray(_data)) {
              boo = !this.jnpf.isEmptyArray(_data);
            } else {
              boo = !this.jnpf.isEmpty(_data);
            }
            if (!boo) {
              messageList.push(name + "不能为空");
            }
          }
        }
      }
      isOk = messageList.length == 0;
      if (messageList.length > 0) {
        this.$message.error(messageList[0], 1000)
      }
      return isOk;
    },
    dataAll(){
    },
    goBack() {
      this.$emit('refresh')
    },
    init(data) {
      if(data.flowTaskInfo!=null){

        this.dataInfo(data.flowTaskInfo.flowFormContentJson)

      }else{
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
        this.loading = true
        this.dataForm.id = data.id || ''
        this.setting = data
        this.visible = true;
        this.updateDataRule()
        this.$nextTick(() => {
          this.$refs['elForm'].resetFields();
          if(this.dataForm.id){
            let url  = '/api/zcgl/fico/bill/getBillInfo/' + this.dataForm.id
            if(this.dataForm.flowtaskid){
              url+='?flowtaskid='+this.dataForm.flowtaskid
            }
            request({
              url: url,
              method: 'get'
            }).then(res => {
              this.dataInfo(res.data)
            })
          }
          this.loading = false
          this.$emit('setPageLoad')
        })
      }


    },
    // 表单提交
    dataFormSubmit(eventType,flowUrgent) {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          if (!this.exist()) return
          if (eventType === 'audit' || eventType === 'reject') {
            var _data =this.dataList()
            this.$emit('eventReceiver', _data, eventType)
            return
          }
          this.dataForm.status = eventType === 'submit' ? 0 : 1
          this.dataForm.flowUrgent = flowUrgent
          this.dataForm.flowId = this.setting.flowId;
          this.eventType = eventType
          if (this.eventType === 'submit') {
            this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
              type: 'warning'
            }).then(() => {
              this.request()
            }).catch(() => { });
          } else {
            this.request()
          }
        }
      })
    },
    request() {
      var _data =this.dataList()
      let url = '/api/zcgl/fico/bill'
      if (!this.dataForm.id) {
        delete (this.dataForm.id)
        request({
          url: url,
          method: 'post',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('close', true)
            }
          })
        })
      }else{
        url+='/'+this.dataForm.id
        if(this.dataForm.flowtaskid){
          url+='?flowtaskid='+this.dataForm.flowtaskid
        }
        request({
          url: url,
          method: 'PUT',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('close', true)
            }
          })
        })
      }
    },
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return true
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.read
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return !item.write
    },
    judgeRequired(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.required
    },
    addzcbillitemList(){
      this.tableKey = 'zcbillitemList';
      let item = {
        expenseItem:undefined,
        receiveAmount:undefined,
      }
      this.dataForm.zcbillitemList.push(item)
    },
    delzcbillitemList(index) {
      this.dataForm.zcbillitemList.splice(index, 1);
    },
    dataList(){
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      for(let i=0;i<_data.zcbillitemList.length;i++){
        var _list = _data.zcbillitemList[i];
        _list.expenseItem = _list.expenseItem
      }
      return _data;
    },
    dataInfo(dataAll){
      let _dataAll =dataAll
      for(let i=0;i<_dataAll.zcbillitemList.length;i++){
        var _list = _dataAll.zcbillitemList[i];
        _list.expenseItem = _list.expenseItem
      }
      this.dataForm=_dataAll
    },
    addForSelect(data){
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        this.dataForm[this.tableKey].push(item)
      }
    },
  },
}

</script>
